package net.shopxx.action.member;

import java.io.IOException;
import java.math.BigDecimal;

import javax.annotation.Resource;

import net.shopxx.action.shop.PaymentAction.PaymentResult;
import net.shopxx.bean.Pager;
import net.shopxx.common.CommentUtil;
import net.shopxx.entity.Order;
import net.shopxx.entity.OrderItem;
import net.shopxx.entity.OrderLog;
import net.shopxx.entity.PaymentConfig;
import net.shopxx.entity.Product;
import net.shopxx.entity.Refund;
import net.shopxx.entity.Refundnote;
import net.shopxx.entity.Order.ShippingStatus;
import net.shopxx.entity.OrderLog.OrderLogType;
import net.shopxx.entity.Payment.PaymentType;
import net.shopxx.service.DeliveryCorpService;
import net.shopxx.service.HtmlService;
import net.shopxx.service.MemberService;
import net.shopxx.service.OrderLogService;
import net.shopxx.service.OrderService;
import net.shopxx.service.ProductService;
import net.shopxx.service.ReceiverService;
import net.shopxx.service.RefundService;
import net.shopxx.service.ShippingService;
import net.shopxx.util.ArithUtil;
import net.shopxx.util.PayUtil;
import net.shopxx.util.SystemConfigUtil;

import org.apache.commons.lang.StringUtils;
import org.apache.struts2.convention.annotation.ParentPackage;

import chinapnr.SecureLink;

/**
 * 后台Action类 - 发货
 */

@ParentPackage("member")
public class RefundAction extends BaseMemberAction {

	private static final long serialVersionUID = 3763457558863574061L;

	private Refund refund;
	
	private String processStatus;
	private Refundnote refundnote;
	

	private PaymentType paymentType;// 支付类型
	private BigDecimal amountPayable;// 应付金额（不含支付费用）
	private BigDecimal paymentFee;// 支付手续费
	private PaymentResult paymentResult;// 支付结果
	private PaymentConfig paymentConfig;// 支付方式
	private String payUrl = "http://mas.chinapnr.com/gar/RecvMerchant.do";
	private String refundUrl = "http://mas.chinapnr.com/gao/entry.do";
	private String version = "10";
	private String cmdId = "Buy";
	private String merId = "870708";
	private String ordId = "";
	private String oldOrdId = "";
	private String ordAmt = "";
	private String curCode = "RMB";
	private String pid = "";
	private String retUrl = SystemConfigUtil.getSystemConfig().getShopUrl()+"xysc/pay/huifu!paynotify.action";
	private String bgRetUrl = SystemConfigUtil.getSystemConfig().getShopUrl()+"xysc/pay/huifu!payret.action";
	private String refundRetUrl = SystemConfigUtil.getSystemConfig().getShopUrl()+"xysc/pay/huifu!refund.action";
	private String merPriv = "";
	private String gateId = "";
	private String usrMp = "";
	private String divDetails = "";
	private String payUsrId = "";
	private String chkValue = "";
	private String privateKey = "MerPrK870708.key";

	@Resource
	private RefundService refundService;
	@Resource
	private ShippingService shippingService;
	@Resource
	private MemberService memberService;
	@Resource
	private DeliveryCorpService deliveryCorpService;
	@Resource
	private OrderService orderService;
	@Resource
	private ReceiverService receiverService;
	@Resource
	private OrderLogService orderLogService;
	@Resource
	private ProductService productService;
	@Resource
	private HtmlService htmlService;
	
	

	// 查看
	public String view() {
		refund = refundService.load(id);
		getRequest().setAttribute("receiverSet", memberService.load(refund.getOrder().getSaler()).getReceiverSet());
		return VIEW;
	}
	
	// 查看
	public String process() {
		refund = refundService.load(id);
		return "process";
	}
	
	// 退款处理
	public String processSave() {
		Refund entity = refundService.load(id);
		entity.setRefundStatus(Refund.RefundStatus.processed);
		entity.setProcessStatus(Enum.valueOf(Refund.ProcessStatus.class,
				processStatus));
		
		entity.setReceiver(receiverService.load(refund.getReceiver().getId()));
		
		entity.setSalerReason(refund.getSalerReason());
		refundService.update(entity);
		
		redirectionUrl = "refund!view.action?id="+entity.getId();
		try {
			getResponse().sendRedirect(redirectionUrl);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}

	// 列表
	public String list() {
		if(pager==null)
			pager = new Pager();
		pager.getWhereClause().put("order.saler", getLoginMember().getId());
		pager = refundService.findByPager(pager);
		return LIST;
	}

	// 确认收货
	public String confirm() {
		try {
			//退款
			refund = refundService.load(id);
			Order order = refund.getOrder();
			if (order == null || StringUtils.isEmpty(order.getId())) {
				addActionError("订单信息错误！");
				return ERROR;
			}
			order = orderService.load(order.getId());
			paymentConfig = order.getPaymentConfig();
			paymentFee = order.getPaymentFee();
			amountPayable = order.getTotalAmount().subtract(paymentFee).subtract(
					order.getPaidAmount());
			ordId= order.getOrderSn();
			oldOrdId= order.getOrderSn();
			ordAmt = ArithUtil.getDecimals(order.getTotalAmount());
			divDetails = order.getDivDetails();
			cmdId = "Refund";
			String MerKeyFile = CommentUtil.class.getClassLoader().getResource("").getPath()+privateKey; 
			String	MerData = version + cmdId + merId 
//			+ divDetails 
			+ ordAmt + ordId + oldOrdId;	
			SecureLink secureLink = new SecureLink();
			int ret = secureLink.SignMsg(merId, MerKeyFile, MerData);
			if (ret != 0) {
				addActionError("签名错误 ret=！" + ret);
				return ERROR;
			}
			chkValue = secureLink.getChkValue();
			
			StringBuffer sb = new StringBuffer();
			sb.append("Version="+version);
			sb.append("&CmdId="+cmdId);
			sb.append("&MerId="+merId);
//			sb.append("&DivDetails="+divDetails);
			sb.append("&RefAmt="+ordAmt);
			sb.append("&OrdId="+ordId);
			sb.append("&OldOrdId="+oldOrdId);
//			sb.append("&BgRetUrl="+refundRetUrl);
			sb.append("&ChkValue="+chkValue);
			try {
				String resp = PayUtil.getNetConn(refundUrl, sb.toString());
				if(resp.contains("RespCode=000000"))
				{
					if (order == null) {
						return "error";
					}
					// 库存处理
					if (order.getPaymentStatus() == Order.PaymentStatus.paid
							&& order.getShippingStatus() == ShippingStatus.unshipped) {
						for (OrderItem orderItem : order.getOrderItemSet()) {
							Product product = orderItem.getProductitem()
							.getProduct();
							if (product.getStore() != null) {
								product.setFreezeStore(product.getFreezeStore()
										- orderItem.getProductQuantity());
								productService.update(product);
								if (product.getIsOutOfStock()) {
									htmlService
									.productContentBuildHtml(product);
								}
							}
						}
					}
					order.setPaymentStatus(Order.PaymentStatus.refunded);
					orderService.update(order);
					
					// 订单日志
					OrderLog orderLog = new OrderLog();
					orderLog.setOrderLogType(OrderLogType.payment);
					orderLog.setOrderSn(order.getOrderSn());
					orderLog.setOperator("");
					orderLog.setInfo("退款["+order.getTotalAmount()+"]成功");
					orderLog.setOrder(order);
					orderLogService.save(orderLog);
				}
				else
				{
					addActionError("退款失败");
					return ERROR;
				}
			} catch (Exception e) {
				addActionError("网络错误");
				return ERROR;
			}
			
			
			refund.setShippingStatus(Refund.ShippingStatus.confirmed);
			refund.setRefundStatus(Refund.RefundStatus.completed);
			refundService.update(refund);

			// close order
			
			order.setOrderStatus(Order.OrderStatus.closed);
			order.setPaymentStatus(Order.PaymentStatus.refunded);
			orderService.update(order);
		} catch (Exception e) {
			e.printStackTrace();
		}
		redirectionUrl = "refund!view.action?id="+refund.getId();
		try {
			getResponse().sendRedirect(redirectionUrl);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}

	//留言
	public String savenote() {
		Refund entity = refundService.load(id);
		refundnote.setRefund(entity);
		refundnote.setMember(getLoginMember());
		entity.getRefundnoteSet().add(refundnote);
		refundService.update(entity);
		redirectionUrl = "refund!view.action?id="+entity.getId();
		try {
			getResponse().sendRedirect(redirectionUrl);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}
	

	public String confirmShippAddr() {
		Refund entity = refundService.load(id);
		entity.setReceiver(receiverService.load(refund.getReceiver().getId()));
		refundService.update(entity);
		redirectionUrl = "refund!view.action?id="+entity.getId();
		try {
			getResponse().sendRedirect(redirectionUrl);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}
	
	public Refund getRefund() {
		return refund;
	}

	public void setRefund(Refund refund) {
		this.refund = refund;
	}

	public String getProcessStatus() {
		return processStatus;
	}

	public void setProcessStatus(String processStatus) {
		this.processStatus = processStatus;
	}

	public Refundnote getRefundnote() {
		return refundnote;
	}

	public void setRefundnote(Refundnote refundnote) {
		this.refundnote = refundnote;
	}

}